package com.simple.annotation.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ReflectUtil;
import com.simple.annotation.Action;
import com.simple.core.impl.EnhanceReceiver;
import com.simple.manager.impl.InstanceManager;

import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

public class ActionImpl {

    public static void init() {
        InstanceManager instance = InstanceManager.getInstance();
        for (Object value : instance.values()) {
            Method[] methods = ReflectUtil.getMethods(value.getClass());
            List<Method> list = Arrays.stream(methods)
                    .filter(method -> Objects.nonNull(method.getDeclaredAnnotation(Action.class)))
                    .collect(Collectors.toList());
            if (CollUtil.isEmpty(list)) {
                continue;
            }
            for (Method method : list) {
                EnhanceReceiver enhanceReceiver = new EnhanceReceiver(value, method);
                Action action = method.getDeclaredAnnotation(Action.class);
                Arrays.stream(action.value()).forEach(enhanceReceiver::addAction);
                enhanceReceiver.register();
            }
        }
    }
}
